#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if.h> //  struct ifreq ifr;  结构体的声明
#include <string.h>
#include <unistd.h>

void get_sockt(int sockfd)
{
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    int ret = getsockname(sockfd, (struct sockaddr *)&addr, &len);
    if (ret < 0)
    {
        perror("getsockname");
        return;
    }
    printf("IP:%s\n", inet_ntoa(addr.sin_addr));
    printf("Port:%d\n", ntohs(addr.sin_port));
}

int main(int argc, char const *argv[])
{
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket");
        return -1;
    }

    get_sockt(sockfd);

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8080);
    addr.sin_addr.s_addr = inet_addr("172.27.208.36");

    // 绑定
    int ret = bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
    if (ret < 0)
    {
        perror("bind");
        return -1;
    }
    get_sockt(sockfd);
    close(sockfd);
    return 0;
}
